//
//  SingleSportEngine.swift
//  LKSportManagerSDK
//
//  Created by KuaiKuai on 2023/8/23.
//

import UIKit
import Foundation
public class SingleSportEngine: NSObject {
    //运动ID
    var sportid: String = ""
    // 运动类型
    var sportType: Int = 0
    // 用户配置
   public var userConfig: UserConfig
    // 运动数据引擎
   public var sportDataEngine: SportDataEngineInterface?
    // 计算引擎
   public var calculateEngine: SportCalculateEngineInterface?
    // 代理
    weak var delegate: SportDataCalculateEngineDelegate?
    /// 计算定时器
    var sumTimer: Timer?
    // 运动记录
    var sportRecord: SportRecordModel?
    
    static let FinalMarkKey = "FinalMark"
    
    var finalMark: Int = 0
    
   public init(userConfig: UserConfig) {
        self.userConfig = userConfig
    }
    // 开始运动
   public func startSport() {
       
       if sportDataEngine == nil {
          sportDataEngine = DefaultSportDataEngine()
       }
       if calculateEngine == nil {
           calculateEngine = DefaultSportCalculateEngine(user: userConfig)
       }
       if sportRecord == nil {
           finalMark = getFinalMark()
           finalMark += 1
           let sptRcdUUID: String = userConfig.id + sportid + String(finalMark)
           sportRecord = SportRecordModel(uuid: sptRcdUUID, id: String(sportType), userid: userConfig.id)
       }
       self.calculateEngine?.sportRecord = sportRecord
       startSumTimer()
    }
    // 暂停运动
    public func pauseSport() {
        sumTimer?.invalidate()
        sumTimer = nil
    }
    // 继续运动
    public func continueSport() {
        if sportDataEngine == nil {
            return
        }
        if calculateEngine == nil {
            return
        }
        startSumTimer()
    }
    // 结束运动
    public func endSport() {
        sumTimer?.invalidate()
        sumTimer = nil
        sportRecord = nil
        self.calculateEngine?.sportRecord = nil
        setFinalMark()
    }
    func startSumTimer() {
        if sumTimer != nil {
            return
        }
        sumTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            guard let weakself = self else {
                return
            }
            weakself.sumTask()
        }
        RunLoop.current.add(sumTimer!, forMode: .common)
    }
    func sumTask() {
        
        let spCongfig = self.sportDataEngine?.getSportConfig(user: userConfig)
        let dataModel = self.sportDataEngine?.getSportData(user: userConfig)
        if let modVal = dataModel, let spcfgVal = spCongfig {
            self.calculateEngine?.calculate(sportConfig: spcfgVal, data: modVal)
        }
    }
    func getFinalMark() -> Int {
        
        let finalMark = UserDefaults.standard.object(forKey: SingleSportEngine.FinalMarkKey)
        if let markDic = finalMark as? Dictionary<String, Int> {
            if let lastIndex = markDic[userConfig.id] {
                return lastIndex
            }else {
                return 1
            }
        }else {
            return 1
        }
    }
    func setFinalMark() {
        let dic = UserDefaults.standard.object(forKey: SingleSportEngine.FinalMarkKey)
        if var markDic = dic as? Dictionary<String, Int> {
            markDic[userConfig.id] = finalMark
            UserDefaults.standard.set(markDic, forKey: SingleSportEngine.FinalMarkKey)
        }else {
            
            let markDic = [userConfig.id:finalMark]
            UserDefaults.standard.set(markDic, forKey: SingleSportEngine.FinalMarkKey)
        }
        
    }
}

/********运动计算引擎代理**********/
public protocol SportDataCalculateEngineDelegate: NSObject {
    // 计算完成
    func calculateCompletion(user: UserConfig, record: SportRecordModel)
    // 心率等级升级
    func heartRateLevelUpgrad(user: UserConfig, level: SportHeartRateLevel)
    // 心率等级降级
    func heartRateLevelReduce(user: UserConfig, level: SportHeartRateLevel)
    // 进入火力全开状态
    func onEnterFireState(user: UserConfig)
    // 退出火力全开状态
    func onExitFireState(user: UserConfig)
    
}

